package com.hycc.base;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class JUCOradeLock {
    public static void main(String[] args) {
        Data3 data = new Data3();
        new Thread(()->{for (int i = 0; i < 10; i++) data.printA(); },"a").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.printB(); },"b").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.printC(); },"c").start();

    }
}


//判断等待，业务，通知
//按 a b c 顺序执行
class Data3{
    private int number = 1; //1A 2B 3C
    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void printA(){
        lock.lock();
        try {
            while(number!=1){
                //等待
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number=2;
            System.out.println(Thread.currentThread().getName()+"-->AAA");
            //通知
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }

    public void printB(){
        lock.lock();
        try {

            while(number!=2){
                //等待
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number=3;
            System.out.println(Thread.currentThread().getName()+"-->BBB");
            //通知
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }

    public void printC(){
        lock.lock();
        try {

            while(number!=3){
                //等待
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            number=1;
            System.out.println(Thread.currentThread().getName()+"-->CCC");
            //通知
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }
}